package com.ldx.forkjoin;

/**
 * @author lidexin
 * @create 2021-10-17 12:18
 */

import java.util.concurrent.RecursiveTask;

/***
 * 求和计算
 * 如何使用forkjoin
 * 1.forkJoinPool 通过他来执行
 * 2.计算任务 forkjoinPool.execute(ForkJoinTask<?> task)
 *
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;

    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {
//        int sum = 0;
//        for (int i = 1; i <= 10_0000_0000; i++) {
//            sum += i;
//        }
//        System.out.println(sum);
    }


    @Override
    protected Long compute() {
        if((end -start)< temp ) {
            //分支合并计算
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
           return sum;
        }else { //forkjoin 递归
           long middle = (start + end) / 2;//中间值
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();//拆分任务，把任务压入线程队列
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
            task2.fork();//拆分任务，把任务压入线程队列

            return task1.join() + task2.join();
        }
    }
}
